package com.GatherFour;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.ChannelListener;
import android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public abstract class WifiDirectManager extends Activity implements ChannelListener, ConnectionInfoListener{
	protected WifiP2pManager manager;
	protected Channel channel;
	protected Player device;
	//private WifiP2pDevice device;
	protected WifiP2pInfo info;
	private BroadcastReceiver receiver = null;
	protected final IntentFilter intentFilter = new IntentFilter();
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

        
        manager = (WifiP2pManager)getSystemService(Context.WIFI_P2P_SERVICE);
        channel = manager.initialize(this, this.getMainLooper(), this);
        if(channel != null){
        	Toast.makeText(WifiDirectManager.this,"Network Initiated",
                    Toast.LENGTH_SHORT).show();
        }
        
        //receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
		
	
    }
    
    
    @Override
    public void onResume() {
        super.onResume();
        receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
        registerReceiver(receiver, intentFilter);
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(receiver);

    }
    
    @Override
    protected void onStop() {
        super.onStop();
        //manager.removeGroup(channel, null);
        // The activity is no longer visible (it is now "stopped")
    }

	@Override
	public void onChannelDisconnected() {
		// TODO Auto-generated method stub
		//manager.removeGroup(channel, null);
        manager = (WifiP2pManager)getSystemService(Context.WIFI_P2P_SERVICE);
        channel = manager.initialize(this, this.getMainLooper(), this);
		
	}
	
	abstract public void updateThisDevice(WifiP2pDevice device);
	
	protected void setDeviceStatus(WifiP2pDevice device, int status){
		device.status = status;
	}
	
	
	protected static String getDeviceStatus(int deviceStatus) {
        switch (deviceStatus) {
            case WifiP2pDevice.AVAILABLE:
                return "Available";
            case WifiP2pDevice.INVITED:
                return "Invited";
            case WifiP2pDevice.CONNECTED:
                return "Connected";
            case WifiP2pDevice.FAILED:
                return "Failed";
            case WifiP2pDevice.UNAVAILABLE:
                return "Unavailable";
            case Player.SERVER:
            	return "Server Available";
            case Player.FULL:
            	return "Full";
            case Player.CLIENT:
            	return "Client";
            default:
                return "Unknown";

        }
    }
	
	@Override
	public void onConnectionInfoAvailable(WifiP2pInfo info) {
		// TODO Auto-generated method stub
		this.info = info;
		TextView view = (TextView) findViewById(R.id.my_name);
        view.setText(info.groupOwnerAddress.getHostAddress());
        view = (TextView) findViewById(R.id.my_status);
        view.setText(info.isGroupOwner?"True":"False");
        
        
        new Thread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					ServerSocket socket = new ServerSocket(8988);
					Socket server = socket.accept();
					
					final String serverAddr = server.getInetAddress().getHostAddress();
					final Scanner sc = new Scanner(server.getInputStream());
					if(sc.hasNextLine()){
						runOnUiThread(new Runnable(){

							@Override
							public void run() {
								// TODO Auto-generated method stub
								TextView view =(TextView) findViewById(R.id.my_status);
								view.setText("address:"+serverAddr);
							}
							
						});
					}else{
						
					}
					
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
        	
        }).start();
      
	}
	
	

}
